import React, { useState, useEffect } from 'react';
import { Form, Icon, Row, message, Modal, Spin, Popconfirm, Col, Radio } from 'antd';
import { history } from 'umi'
import { connect } from 'umi';
import { useRequest, defaultFormatResult } from '@/hooks';
import { updateCandidateInfo } from '@/pages/RecruitEmail/service/hire';
import { ContactItem, Salary } from '@/pages/RecruitEmail/pc/containers';
import { InterviewBoxPc, FormHeader, DeclareInfo, ButtonPc as Button } from '@/pages/RecruitEmail/pc/components';
import pic from '@/pages/RecruitEmail/images/interview-bg-accept.png';
import { useInterviewCandidate } from '@/pages/RecruitEmail/hooks';
import styles from './index.less';

const WorkStatus = {
    1: '在职',
    2: '离职',
    3: '应届生'
};
// const { Option } = Select;
const contactPersonStyle = {
    height: 43,
    background: '#F6F7F8',
    borderRadius: 4,
    border: '1px solid #E8EAEF',
    display: 'flex',
    justifyContent: 'space-between',
    alignItems: 'center',
    padding: '0 14px',
    marginBottom: 16
};
const contactInfoStyle = {
    height: 43,
    background: 'transparent',
    borderRadius: 4,
    border: 'none',
    display: 'flex',
    justifyContent: 'space-between',
    alignItems: 'center',
    padding: '0 7px',
    marginBottom: 16,
    fontFamily: 'PingFangSC-Medium',
    fontSize: '16px',
    color: 'rgba(0,0,0,0.85)',
    fontWeight: '500'
};
// const titleProps = {
//     titleRender: styleTitle,
//     showButton: false
// };

// const oneLineLayout = { labelCol: { span: 6 } };

/**
 * 根据编辑状态返回组件
 * @param {*} EditComponent 编辑状态对应组件
 * @param {*} ViewComponent 展示状态对应组件
 * @param {*} editFlag 是否为编辑状态
 */
const renderItem = (EditComponent, ViewComponent, editFlag = true) => (editFlag ? EditComponent : ViewComponent);

const ID_PREFIX = 'NEW_';

// const editLayout = {
//     layout: 'vertical'
//     // wrapperCol: { span: 18 }
// };

// const viewLayout = {
//     layout: 'vertical'
//     // labelCol: { span: 2 },
//     // wrapperCol: { span: 14 }
// };

const InterviewCandidate = ({ maxContactNum, defaultArr, dispatch, needBackgroundFlag, nid, form }) => {
    const { getFieldDecorator } = form;
    const { data: talentInfo, loading } = useInterviewCandidate(nid);
    // 候选人信息
    // const { loading, data: talentInfo = {} } = useRequest(() => getCandidateInfo(signCandidateId), {
    //     refreshDeps: [signCandidateId],
    //     ...defaultFormatResult
    // });

    // 保存候选人信息
    const { loading: submitLoading, run: runSubmit } = useRequest(updateCandidateInfo, {
        manual: true,
        ...defaultFormatResult
    });

    const [contacts, setContacts] = useState([]); // 联系人
    const [infoState, setInfoState] = useState(form.getFieldValue('remove')); // 是否同意背调
    useEffect(() => {
        // 生成默认数据
        if (needBackgroundFlag) {
            // talentInfo?.backgroundFlag !== 1 用于判断是否可以编辑
            let defaultLength = 3;
            if (talentInfo?.recruitTalentBackgrounds?.length) {
                defaultLength -= talentInfo?.recruitTalentBackgrounds?.length; // 剔除已有的
            }
            if (talentInfo?.backgroundFlag === 1) {
                defaultLength = 0;
            }
            if (defaultLength >= 0) {
                dispatch({
                    type: 'defaultBGList/init',
                    backgroundNum: defaultLength,
                    ID_PREFIX
                });
            }
        }
    }, [needBackgroundFlag, talentInfo]);

    /**
     * 检查联系人数量上限,控制添加按钮显示隐藏
     */
    const showAddButton = () => {
        const tempArr = contacts.filter(item => !item.delete);
        if (tempArr.length >= maxContactNum) {
            return false;
        }
        return true;
    };

    // const hasWorkExp = talentInfo?.recruitTalentBackgroundSalary?.talentWorkType === 1;
    const hasWorkExp = React.useMemo(() => {
        const status = form.getFieldValue('recruitTalentBackgroundSalary.lastPostStatus');
        console.log('status-----', status);
        // eslint-disable-next-line eqeqeq
        if (status == 3) {
            setInfoState(false);
            setContacts([]);
            return false;
        }
        return true;
    }, [form.getFieldValue('recruitTalentBackgroundSalary.lastPostStatus')]);
    useEffect(() => {
        if (!hasWorkExp) {
            return;
        }
        if (talentInfo?.recruitTalentBackgrounds?.length) {
            // setContacts(
            //     talentInfo?.recruitTalentBackgrounds?.map(item => ({
            //         id: item.id,
            //         delete: false
            //     }))
            // );
            setContacts([...talentInfo?.recruitTalentBackgrounds, ...defaultArr]); // 已填写过背调信息的回显
            form.setFieldsValue({
                remove: true
            });
        } else {
            // setContacts([{ id: `${ID_PREFIX}0` }]);
        }
        if (talentInfo?.backgroundFlag === 1) {
            // message.info('您已提交过相关信息！');
            form.setFieldsValue({
                remove: true
            });
        }
    }, [talentInfo, defaultArr]);

    const generateId = () => {
        if (!contacts.length) {
            return 0;
        }
        const nextId = Math.max(...contacts.map(item => Number(String(item.id).replace(ID_PREFIX, '')))) + 1;
        return ID_PREFIX + nextId;
    };
    useEffect(() => {
        if (!hasWorkExp) {
            return;
        }
        const state = form.getFieldValue('remove'); // 是否同意背调
        if (state) {
            if (contacts?.length === 0 || contacts?.filter(item => !item.delete)?.length === 0) {
                // 联系人为空数组时，创建初始数据
                // setContacts([
                //     {
                //         id: `${ID_PREFIX}0`
                //     }
                // ]);
                setContacts([...defaultArr]);
            }
        }
        if (infoState && !state) {
            Modal.confirm({
                title: '确定拒绝声明内容',
                content: '拒绝声明内容将清空背调联系人信息',
                okText: '确定',
                cancelText: '取消',
                onOk: () => {
                    setContacts([]);
                    // console.log(form.getFieldsValue());
                    setInfoState(state);
                },
                onCancel() {
                    setInfoState(true);
                    form.setFieldsValue({
                        remove: true
                    });
                }
            });
        } else {
            setInfoState(state);
        }
    }, [form.getFieldValue('remove'), JSON.stringify(contacts), infoState, defaultArr]); // 背调声明前的ckeckbox驱动变化

    const isEdit = talentInfo?.backgroundFlag !== 1;
    // const isEdit = true;

    // const formItemLayout = isEdit ? editLayout : viewLayout;

    const commonProps = {
        form,
        talentInfo,
        // oneLineLayout,
        renderItem,
        isEdit,
        hasWorkExp
    };

    const handleAdd = () => {
        setContacts([
            ...contacts,
            {
                id: generateId()
            }
        ]);
    };

    // eslint-disable-next-line no-shadow
    const handleRemove = id => {
        // 需要标记删除服务端
        if (talentInfo?.recruitTalentBackgrounds?.some(item => item.id === id)) {
            setContacts(
                contacts.map(item => {
                    if (id === item.id) {
                        return {
                            ...item,
                            delete: true
                        };
                    }
                    return item;
                })
            );
        } else {
            setContacts(contacts.filter(item => item.id !== id));
        }
    };

    /**
     * 提交到服务器
     */
    const handleSubmit = () => {
        const callSubmit = values => {
            Modal.confirm({
                title: '确定要提交吗',
                content: '薪资意向信息无法二次修改',
                okText: '确定',
                cancelText: '取消',
                onOk: async () => {
                    const { recruitTalentBackgroundSalary = {}, recruitTalentBackgrounds = [] } = values;
                    const { salaryProveRelationsFileList, ...rest } = recruitTalentBackgroundSalary;
                    let postParams = null;
                    if (hasWorkExp) {
                        postParams = {
                            employId: talentInfo.employId,
                            lastPostStatus: Number(rest?.lastPostStatus),
                            recruitTalentBackgroundSalary: {
                                ...rest
                            },
                            recruitTalentBackgrounds: contacts.map(item => {
                                if (item.delete) {
                                    return {
                                        id: item.id,
                                        operationType: 2
                                    };
                                }
                                const bgData = recruitTalentBackgrounds[item.id];
                                const insertUpdateProps = String(item.id).includes(ID_PREFIX)
                                    ? {
                                          operationType: 0
                                      }
                                    : {
                                          operationType: 1,
                                          id: item.id
                                      };

                                return {
                                    ...bgData,
                                    ...insertUpdateProps,
                                    backgroundTime: bgData.backgroundTime.format('YYYY-MM-DD HH:mm:ss')
                                };
                            })
                        };
                    } else {
                        postParams = {
                            employId: talentInfo.employId,
                            lastPostStatus: Number(rest?.lastPostStatus),
                            recruitTalentBackgroundSalary: {
                                // ...rest
                                expectMonthNumber: rest?.expectMonthNumber,
                                expectSalary: rest?.expectSalary
                            },
                            recruitTalentBackgrounds: null
                        };
                    }
                    console.log(postParams);
                    const result = await runSubmit(postParams);
                    if (result) {
                        console.log(postParams);
                        message.success('提交成功');
                        setTimeout(() => {
                            history.go(0);
                        }, 2000);
                    }
                },
                onCancel() {
                    console.log('Cancel');
                }
            });
        };
        // 校验
        form.validateFieldsAndScroll((errors, values) => {
            // if (errors) return;
            if (errors?.remove?.errors.length) {
                message.error(errors?.remove?.errors[0].message);
            }
            if (hasWorkExp && errors) {
                return;
            }
            if (!hasWorkExp) {
                if (
                    errors?.recruitTalentBackgroundSalary?.expectMonthNumber ||
                    errors?.recruitTalentBackgroundSalary?.expectSalary
                ) {
                    return;
                }
            }
            console.log(errors, values);
            callSubmit(values);
        });
    };

    // eslint-disable-next-line no-shadow
    // const getContactDetail = id => talentInfo?.recruitTalentBackgrounds?.find(item => item.id === id);

    // const bannerText = (
    //     <>
    //         <div>
    //             欢迎应聘 <strong>{talentInfo?.recruitTalentBackgroundSalary?.companyName}</strong>
    //         </div>
    //         <div>请提供薪资及背调联系人信息</div>
    //     </>
    // );

    return (
        <div className={styles.interviewPc}>
            <InterviewBoxPc
                titleProps={{
                    // titleAfter: companyName,
                    title: isEdit ? '恭喜您通过面试！' : '您已通过面试并提供相关信息',
                    content: isEdit
                        ? '请提供您的薪资意向和其他必要信息'
                        : 'HR收到信息后将与您进行下一步沟通，请耐心等待',
                    wrap: !isEdit,
                    sort: !isEdit,
                    src: pic,
                    iconType: isEdit ? '' : 'accept',
                    iconStyle: {
                        color: '#44C69D',
                        marginRight: 12
                    },
                    picStyle: {
                        marginLeft: 75,
                        marginBottom: 16,
                        marginTop: 21
                    }
                }}
                boxProps={{
                    style: {
                        padding: '32px 24px'
                    }
                }}
                showTip={false}
            >
                <Spin spinning={loading}>
                    <div
                        style={{
                            margin: '0 60px 0 140px'
                        }}
                    >
                        <div
                            style={{
                                display: 'flex',
                                flexDirection: isEdit ? 'column' : 'row'
                            }}
                        >
                            <div className={styles.title}>
                                <span>
                                    应聘职位：
                                    {talentInfo?.recruitTalentBackgroundSalary?.dutyName}
                                </span>
                            </div>
                            {!isEdit ? (
                                <>
                                    <div className={styles.status}>
                                        {WorkStatus[talentInfo?.recruitTalentBackgroundSalary?.lastPostStatus]
                                            ? '状态：'
                                            : ''}
                                        <span
                                            style={{
                                                color: 'rgba(0,0,0,0.85)',
                                                fontWeight: '400'
                                            }}
                                        >
                                            {WorkStatus[talentInfo?.recruitTalentBackgroundSalary?.lastPostStatus]}
                                        </span>
                                    </div>
                                    <div className={styles.apply}>
                                        应聘日期：
                                        <span
                                            style={{
                                                color: 'rgba(0,0,0,0.85)',
                                                fontWeight: '400'
                                            }}
                                        >
                                            {talentInfo?.recruitTalentBackgroundSalary?.acceptDate}
                                        </span>
                                    </div>
                                    <div
                                        style={{
                                            display: 'none'
                                        }}
                                    >
                                        {getFieldDecorator('recruitTalentBackgroundSalary.lastPostStatus', {
                                            initialValue:
                                                // eslint-disable-next-line max-len
                                                talentInfo?.recruitTalentBackgroundSalary?.lastPostStatus?.toString() ||
                                                '1',
                                            rules: [
                                                {
                                                    required: true,
                                                    message: '请选择工作状态'
                                                    // whitespace: true
                                                }
                                            ]
                                        })(
                                            <Radio.Group>
                                                <Radio value="1">在职</Radio>
                                                <Radio value="2">离职</Radio>
                                                <Radio value="3">应届生</Radio>
                                            </Radio.Group>
                                            // <Select placeholder="请选择状态" style={{ width: '100%' }}>
                                            //     <Option value="2" label="离职">
                                            //         离职
                                            //     </Option>
                                            //     <Option value="1" label="在职">
                                            //         在职
                                            //     </Option>
                                            //     <Option value="3" label="应届生">
                                            //         应届生
                                            //     </Option>
                                            // </Select>
                                        )}
                                    </div>
                                </>
                            ) : (
                                <div className={styles.formWrapNewStatus}>
                                    <Row>
                                        <Col span={12}>
                                            <Form.Item
                                                style={{
                                                    color: 'rgba(0,0,0,0.45)'
                                                }}
                                                label="工作状态"
                                                layout="horizontal"
                                                labelCol={{
                                                    span: 4
                                                }}
                                                wrapperCol={{
                                                    span: 14
                                                }}
                                            >
                                                {getFieldDecorator('recruitTalentBackgroundSalary.lastPostStatus', {
                                                    initialValue:
                                                        // eslint-disable-next-line max-len
                                                        talentInfo?.recruitTalentBackgroundSalary?.lastPostStatus?.toString() ||
                                                        '1',
                                                    rules: [
                                                        {
                                                            required: true,
                                                            message: '请选择工作状态'
                                                            // whitespace: true
                                                        }
                                                    ]
                                                })(
                                                    <Radio.Group>
                                                        <Radio value="1">在职</Radio>
                                                        <Radio value="2">离职</Radio>
                                                        <Radio value="3">应届生</Radio>
                                                    </Radio.Group>
                                                    // <Select placeholder="请选择状态" style={{ width: '100%' }}>
                                                    //     <Option value="2" label="离职">
                                                    //         离职
                                                    //     </Option>
                                                    //     <Option value="1" label="在职">
                                                    //         在职
                                                    //     </Option>
                                                    //     <Option value="3" label="应届生">
                                                    //         应届生
                                                    //     </Option>
                                                    // </Select>
                                                )}
                                            </Form.Item>
                                        </Col>
                                        <Col span={12}>
                                            <div className={styles.apply}>
                                                <span>应聘日期：</span>
                                                {talentInfo?.recruitTalentBackgroundSalary?.acceptDate}
                                            </div>
                                        </Col>
                                    </Row>
                                </div>
                            )}
                        </div>
                        <div className={styles.formWrapNew}>
                            {/* <Form {...formItemLayout}> */}
                            <FormHeader title="薪资意向" />
                            {talentInfo ? <Salary {...commonProps} /> : null}
                            {/* 是否需要背调？ */}
                            <div
                                style={{
                                    display: hasWorkExp && needBackgroundFlag ? 'block' : 'none'
                                }}
                            >
                                <>
                                    {(contacts?.length > 0 || isEdit) && <FormHeader title="背调联系人信息" />}
                                    {/* {isEdit && (
                                        <Alert
                                            message="若未提交以下信息，录用前可通过邮件中的链接，再次进入本页面"
                                            type="warning"
                                            showIcon
                                            closable
                                            className={styles.alert}
                                        />
                                    )} */}
                                    {hasWorkExp && isEdit && (
                                        <>
                                            <div className={styles.desc}>同意声明内容后，可添加背调联系人信息</div>
                                            <div
                                                style={{
                                                    color: 'rgba(0,0,0,0.65)',
                                                    fontSize: 14,
                                                    paddingRight: '120px'
                                                }}
                                            >
                                                <DeclareInfo
                                                    form={form}
                                                    disabled={!isEdit}
                                                    needBackgroundFlag={needBackgroundFlag}
                                                    title="本人同意在入职前接受背调，并提供上级主管、平级同事或下属（若有）的联系方式。 公司可对有关的信息进行调查，亦有权查阅本人各种材料以及向第三方做个人访谈（如应聘者原雇主、家庭成员、业务联系人、经济来源人、朋友等）。 由于本人提供虚假信息的，公司方面有权在核实后随时终止劳动合同。"
                                                />
                                            </div>
                                        </>
                                    )}

                                    <div>
                                        {contacts
                                            .filter(item => !item.delete)
                                            .map((item, index) => (
                                                <div key={item.id}>
                                                    <div style={isEdit ? contactPersonStyle : contactInfoStyle}>
                                                        <span
                                                            style={{
                                                                fontFamily: 'PingFangSC-Medium',
                                                                fontSize: '16px',
                                                                color: 'rgba(0,0,0,0.85)',
                                                                fontWeight: '500'
                                                            }}
                                                        >
                                                            联系人 {index + 1}
                                                        </span>
                                                        {contacts?.filter(item1 => !item1.delete)?.length !== 1 &&
                                                            isEdit && (
                                                                <Popconfirm
                                                                    title="确定要删除联系人信息吗？"
                                                                    onConfirm={() => {
                                                                        handleRemove(item.id);
                                                                    }}
                                                                    okText="确定"
                                                                    icon={
                                                                        <Icon
                                                                            type="exclamation-circle"
                                                                            theme="filled"
                                                                            style={{
                                                                                color: '#ffa22d'
                                                                            }}
                                                                        />
                                                                    }
                                                                    cancelText="取消"
                                                                >
                                                                    <Icon
                                                                        type="close-circle"
                                                                        style={{ fontSize: 16, color: '#858B9B' }}
                                                                        theme="filled"
                                                                    />
                                                                </Popconfirm>
                                                            )}
                                                    </div>
                                                    {contacts?.length > 0 && (
                                                        <ContactItem
                                                            {...commonProps}
                                                            workCompanyList={talentInfo?.workCompanyList}
                                                            id={item.id}
                                                            // detail={getContactDetail(item.id)}
                                                            detail={item}
                                                        />
                                                    )}
                                                    {/* <Divider style={{ backgroundColor: '#ededed' }} /> */}
                                                </div>
                                            ))}
                                        {isEdit && form.getFieldValue('remove') && hasWorkExp && showAddButton() && (
                                            <Button
                                                style={{
                                                    width: '100%',
                                                    background: 'rgba(0, 0, 0, 0.05)',
                                                    height: 43,
                                                    border: 'none'
                                                }}
                                                onClick={handleAdd}
                                            >
                                                <Icon type="plus" />
                                                <span
                                                    style={{
                                                        fontFamily: 'PingFangSC-Medium',
                                                        fontSize: '16px',
                                                        color: 'rgba(0,0,0,0.85)',
                                                        fontWeight: '500'
                                                    }}
                                                ></span>
                                                添加联系人
                                            </Button>
                                        )}
                                    </div>
                                </>
                            </div>
                            {/* </Form> */}
                        </div>
                        {isEdit && (
                            <Row
                                type="flex"
                                justify="center"
                                style={{
                                    marginTop: '32px'
                                }}
                            >
                                <Button
                                    style={{
                                        width: 200
                                    }}
                                    type="primary"
                                    onClick={handleSubmit}
                                    loading={submitLoading}
                                    // disabled={!form.getFieldValue('remove') && hasWorkExp}
                                >
                                    提交
                                </Button>
                            </Row>
                        )}
                    </div>
                </Spin>
            </InterviewBoxPc>
        </div>
    );
};

export default connect(({ defaultBGList }) => ({
    defaultArr: defaultBGList.defaultArr,
    maxContactNum: defaultBGList.maxContactNum
}))(Form.create()(InterviewCandidate));
